<?php

include_once ("database.php");
	
$id = $_POST["prodId"];
$name = $_POST["prodName"];
$category = $_POST["prodCategory"];
$subCategory = $_POST["prodSubCategory"];
$price = $_POST["prodPrice"];
	
$connection = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASS, DB_NAME);
	
if ($id == "") {
	addSpecifiedProduct($connection, $name, $category, $subCategory, $price);
}
else {
	editSpecifiedProduct($connection, $id, $name, $category, $subCategory, $price);
}
	
mysqli_close($connection);

header("location:../index.php?content=product_list");

function editSpecifiedProduct($connection, $id, $name, $category, $subcategory, $price)
{
	$stmt = mysqli_prepare($connection, "UPDATE produkty SET nazwa = ?, podkategoria = ?, kategoria = ?, cena = ? WHERE id = ?");
	mysqli_stmt_bind_param($stmt, 'sssdd', $name, $subcategory, $category, $price, $id);
	mysqli_stmt_execute($stmt);
	mysqli_stmt_close($stmt);
}

function addSpecifiedProduct($connection, $name, $category, $subcategory, $price)
{
	$result = mysqli_query($connection, "SELECT max(id) FROM produkty");
	$row = mysqli_fetch_array($result);
	$id = $row[0] + 1;
	
	$stmt = mysqli_prepare($connection, "INSERT INTO produkty VALUES (?, ?, ?, ?, ?)");
	mysqli_stmt_bind_param($stmt, 'dsssd', $id, $name, $subcategory, $category, $price);
	mysqli_stmt_execute($stmt);
	mysqli_stmt_close($stmt);
}
?>